package com.bitin.adorn.modules.system.service.impl;

import com.bitin.adorn.common.exception.BizException;
import com.bitin.adorn.modules.system.domain.Department;
import com.bitin.adorn.modules.system.repository.DepartmentRepository;
import com.bitin.adorn.modules.system.service.DepartmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Mr.Lu
 * @since 2024/6/5 15:16
 */
@Service
@RequiredArgsConstructor
public class DepartmentServiceImpl implements DepartmentService {

    private final DepartmentRepository departmentRepository;

    @Override
    public Department save(Department department) {
        return this.departmentRepository.save(department);
    }

    @Override
    public List<Department> list() {
        return this.departmentRepository.findAll();
    }

    @Override
    public Department findById(Long id) {
        return this.departmentRepository.findById(id).orElseThrow(() -> new BizException(String.format("部门[%s]不存在", id)));
    }

    @Override
    public void deleteById(Long id) {
        this.departmentRepository.deleteById(id);
    }

    @Override
    public Department addChild(Long id, Department department) {
        Department parent = this.departmentRepository.findById(id).orElseThrow(() -> new BizException(String.format("部门[%s]不存在", id)));
        parent.addChild(department);
        return this.departmentRepository.save(parent);
    }

    @Override
    public Department removeChild(Long id, Long childId) {
        Department parent = this.departmentRepository.findById(id).orElseThrow(() -> new BizException(String.format("部门[%s]不存在", id)));
        parent.removeChild(childId);
        return this.departmentRepository.save(parent);
    }
}
